package com.qiche.controller.wx;

import com.aliyuncs.exceptions.ClientException;
import com.qiche.aspect.Result;
import com.qiche.enums.RedisKeyPrefixEnum;
import com.qiche.enums.ResultEnum;
import com.qiche.model.StoreMember;
import com.qiche.redis.RedisService;
import com.qiche.requestpram.MemberRegisterURL;
import com.qiche.service.StoreMemberService;
import com.qiche.util.AliyunSmsUtils;
import com.vdurmont.emoji.EmojiParser;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * @author LB
 *
 * @date 2018年6月4日
 */
@RestController
@RequestMapping(value = "wx/user")
public class WxRegisterController {
	
	private static final Logger log = LoggerFactory.getLogger(WxRegisterController.class);
	
	@Autowired
	private HttpSession session;
	
	@Autowired
	private RedisService redisService;
	
	@Autowired
	private StoreMemberService storeMemberService;
	
	/**
	 * 通过手机号注册
	 *
	 * @param memberRegisterURL
	 * @param result
	 * @return
	 */
	@PostMapping(value = "/register")
	public Result<?> sendValidate(@RequestParam String accessToken,@RequestParam String openid, String unionid,@RequestParam Long merchantId, StoreMember storeMember, @Validated MemberRegisterURL memberRegisterURL, BindingResult result) {
		if (result.hasErrors()) {
			return Result.createByResultEnum(ResultEnum.PARAM_ERROR);
		}

		String code = memberRegisterURL.getCode();
		String memberPhone = memberRegisterURL.getMemberPhone();

		StoreMember member = storeMemberService.selectByPhoneAndMerchantId(memberPhone,merchantId.intValue());
		if (member != null) {
			if (StringUtils.isNotEmpty(member.getUnionid())) {
				return Result.createByResultEnum(ResultEnum.MEMBER_EXIST_BY_PHONE);
			} else {
				if (storeMember.getId() == member.getId()) {
					BeanUtils.copyProperties(member, storeMember);
				}
			}
		}

		//String redisCode = redisManager.getString(RedisKeyPrefixEnum.SEND_MEMBER_WX_BIND_PHONE + memberPhone);
		String redisCode =redisService.get(RedisKeyPrefixEnum.SEND_MEMBER_WX_BIND_PHONE + memberPhone).toString();
		if (redisCode == null) {
			return Result.createByResultEnum(ResultEnum.MEMBER_CODE_TIME_OUT);
		}
		if (!redisCode.equals(code)) {
			return Result.createByResultEnum(ResultEnum.VERIFY_CODE_ERROR);
		}

		storeMember.setPhone(memberPhone);
		storeMember.setName(memberRegisterURL.getMemberName());
		// 去除Emoji表情
		storeMember.setNickname(EmojiParser.removeAllEmojis(storeMember.getNickname()));
		int i = 0;
		if (storeMember.getId() != null) {
			// 需要update
			i = storeMemberService.updateNotNull(storeMember);
		}
		if (i > 0) {
			// 成功
			return Result.createByResultEnum(ResultEnum.SUCCESS);
		} else {
			// 失败
			return Result.createByResultEnum(ResultEnum.FAILURE);
		}
	}

	/**
	 * 注册时,发送验证码
	 *
	 * @param phone
	 * @return
	 * @throws ClientException
	 */
	@PostMapping(value = "/send/sms")
	public Result<?> sendSms(@RequestParam String accessToken,@RequestParam String openid, String unionid,@RequestParam Long merchantId, StoreMember storeMember,@RequestParam("phone") String phone) throws ClientException {

		if (phone == null) {
			return Result.createByResultEnum(ResultEnum.PARAM_ERROR);
		}

		StoreMember member = storeMemberService.selectByPhoneAndMerchantId(phone,merchantId.intValue());
		if (member != null) {
			if (StringUtils.isNotEmpty(member.getUnionid())) {
				// 说明 该手机号 已存在用户
				return Result.createByResultEnum(ResultEnum.MEMBER_EXIST_BY_PHONE);
			}
		}
		// 发送验证码
		String randomCode = AliyunSmsUtils.getRandomCode();
		try {
			AliyunSmsUtils.sendSms(phone, randomCode);
			log.info("{}发送验证码{}成功", phone, randomCode);
			redisService.set(RedisKeyPrefixEnum.SEND_MEMBER_WX_BIND_PHONE + phone, randomCode, 60L);
			//redisManager.set(RedisKeyPrefixEnum.SEND_MEMBER_WX_BIND_PHONE + phone, randomCode, 60);
			return Result.createByResultEnum(ResultEnum.SUCCESS);
		} catch (ClientException e) {
			log.error(e.getMessage(), e);
			return Result.createByResultEnum(ResultEnum.FAILURE);
		}
	}
	
	

}
